﻿define(['jquery', 'backbone', 'underscore', 'views/orderForm.view', 'mediator', 'proxy'], function ($, Backbone, _, orderForm, mediator, proxy) {
    var welcomeView = Backbone.View.extend({
        el: "#main",

        events: {
            "click #editSelected": "edit",
            "click #removeSelected": "remove",
            "click tr": "rowClick"
        },

        initialize: function () {
            this.template = _.template($("#order-list-template").html());
            this.emptyTemplate = _.template($("#order-list-empty-template").html());
            this.subscribe();
        },

        subscribe: function () {
            mediator.subscribe("orders::refresh", this.refresh, this);
        },

        render: function () {
            this.showList();
            $("#newOrder").click(this.create);

            return this;
        },

        refresh: function () {
            this.showList();
        },

        showList: function () {
            var that = this,
                template;

            proxy.getOrders({
                success: function (data) {
                    if (data.length === 0) {
                        template = that.emptyTemplate;
                    } else {
                        template = that.template;
                    }

                    $(that.el).html(template({ orders: data }));
                }
            });
        },

        create: function (e) {
            orderForm.render();
            e.preventDefault();
        },

        edit: function (e) {
            var selectedRow = $(this.el).find("table tr[data-status=selected]"),
                that = this;

            if (selectedRow.length > 0) {
                orderForm.render({ orderId: selectedRow.attr("data-id") });
            }

            e.preventDefault();
        },

        remove: function (e) {
            var selectedRow = $(this.el).find("table tr[data-status=selected]"),
                orderId,
                that = this;

            if (selectedRow.length > 0) {
                orderId = selectedRow.attr("data-id");

                proxy.deleteOrder({
                    data: {
                        orderId: orderId
                    },
                    success: function () {
                        that.refresh();
                    }
                });
            }

            e.preventDefault();
        },

        rowClick: function (e) {
            $(e.currentTarget).parent().find("td").removeAttr("style");
            $(e.currentTarget).find("td").css("background-color", "gray");

            $(e.currentTarget).parent().find("tr").removeAttr("data-status");
            $(e.currentTarget).attr("data-status", "selected");

            e.preventDefault();
        }
    });

    return new welcomeView();
});